# -*- coding: utf-8 -*-

import matplotlib
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
from Graphs import Graphs
import thread

import sys
if sys.version_info[0] < 3:
    import Tkinter as Tk
else:
    import tkinter as Tk

class App(Tk.Frame):

    def __init__(self, parent):

        self.parent = parent
        self.graphs = Graphs()
        self.initUI()
        
    def initUI(self):
        '''
        This method initializes the interface (GUI)
        '''
        self.parent.title("LP")
        self.buildMenu()

        # Frame da direita
        self.sideMenuFrame = Tk.Frame(self.parent)
        self.sideMenuFrame.grid(row = 0, column = 1, sticky = Tk.W+Tk.E+Tk.N+Tk.S, padx=5, pady=5)
        self.buildSideMenu()

        # Frame do gráfico
        self.graphFrame = Tk.Frame(self.parent)
        self.graphFrame.grid(row = 0, column = 0, sticky = Tk.W+Tk.E+Tk.N+Tk.S, padx=5, pady=5)
        self.buildGraph()

    
    def buildMenu(self):
        '''
        This method build the menu bar
        '''
        menubar = Tk.Menu()
        self.parent.config(menu=menubar)

        fileMenu = Tk.Menu(menubar)
        fileMenu.add_command(label="Exit", command=self.exitApp)
        
        menubar.add_cascade(label="Ficheiro", menu=fileMenu)

    def buildSideMenu(self):
        '''
        This method build the side menu (SideMenuFrame items)
        '''
        # Tipo de gŕafico (self.var1)
        graphtype = Tk.Label(self.sideMenuFrame, text="Tipo de gráfico:")
        graphtype.grid(row = 0, column = 0, sticky = Tk.W)
        optionList1 = (u'Gráfico de Barras',
                       u'Gráfico de Linhas',
                       u'Gráfico de Dispersão',
                       u'Gráfico de Linhas (Vários dados)')
        self.var1 = Tk.StringVar()
        self.var1.set(optionList1[0])
        opt1 = Tk.OptionMenu(self.sideMenuFrame, self.var1, *optionList1, command=self.updateDataType)
        opt1.grid(row = 0, column = 1, sticky = Tk.W)

        # Cor do gráfico (self.colorVar)
        colorLabel = Tk.Label(self.sideMenuFrame, text="Cor do gráfico:")
        colorLabel.grid(row = 1, column = 0, sticky = Tk.W)
        colorList = (u'Azul',
                       u'Verde',
                       u'Vermelho',
                       u'Amarelo',
                       u'Preto',
                       u'Branco')
        self.colorVar = Tk.StringVar()
        self.colorVar.set(colorList[1])
        opt1 = Tk.OptionMenu(self.sideMenuFrame, self.colorVar, *colorList)
        opt1.grid(row = 1, column = 1, sticky = Tk.W)
        
        # Tipo de dados (self.var2)
        datatype = Tk.Label(self.sideMenuFrame, text="Tipo de dados:")
        datatype.grid(row = 2, column = 0, sticky = Tk.W)
        
        self.var2data = (u'IPC Global',
                    u'Variação Anual (Taxa de Inflação)',
                    u'Remuneração miníma mensal',
                    u'Remuneração máxima mensal',
                    u'PIB per capita anual',
                    u'Rendimento nacional bruto per capita anual',
                    u'Rendimento disponível bruto per capita anual',
                    u'Remunerações per capita anual')
        nRow = 1
        self.var2 = Tk.StringVar() # IMPORTANTE
        self.var2.set(u'IPC Global')
        for var2 in self.var2data:
            nRow+=1
            b = Tk.Radiobutton(self.sideMenuFrame, text=var2, variable=self.var2, value=var2)
            b.grid(row = nRow, column = 1, sticky = Tk.W)
        
        # Ano de ínicio (self.var3)
        fromyear = Tk.Label(self.sideMenuFrame, text="Desde o ano:")
        fromyear.grid(row = 10, column = 0, sticky = Tk.W)
        optionList3 = self.graphs.getYears(2013)
        self.var3 = Tk.StringVar()
        self.var3.set(optionList3[0])
        opt3 = Tk.OptionMenu(self.sideMenuFrame, self.var3, *optionList3, command=self.updateEndYears)
        opt3.grid(row = 10, column = 1, sticky = Tk.W)
        
        # Ano de fim (self.var4)
        fromyear = Tk.Label(self.sideMenuFrame, text="Até ao ano:")
        fromyear.grid(row = 11, column = 0, sticky = Tk.W)
        self.optionList4 = self.graphs.getYears(1977)
        self.var4 = Tk.StringVar()
        self.var4.set(self.optionList4[-1])
        self.opt4 = Tk.OptionMenu(self.sideMenuFrame, self.var4, *self.optionList4)
        self.opt4.grid(row = 11, column = 1, sticky = Tk.W)

        # Botão gerar gráfico

        showgraph = Tk.Button(self.sideMenuFrame, text="Gerar Gráfico", command=self.updateGraph)
        showgraph.grid(row = 12, column = 1, padx=0, pady=10)

    def updateEndYears(self, val):
        '''
        This method updates the end year OptionMenu
        (Excludes values below the begin year)
        '''
        newList = []
        for item in self.optionList4:
            if int(item) > int(self.var3.get()):
                newList.append(item)

        # Deixa o ano final igual se o inicial mudou para um menor
        if int(self.var3.get()) >= int(self.var4.get()):
            self.var4.set(newList[0])
        self.opt4 = Tk.OptionMenu(self.sideMenuFrame, self.var4, *newList)
        self.opt4.grid(row = 11, column = 1, sticky = Tk.W)

    def updateDataType(self, val):
        '''
        This method updates the Data Type menu
        (When multiple line chart it changes from Radiobutton to Checkbutton)
        '''
        if self.var1.get() == u'Gráfico de Linhas (Vários dados)':
            nRow = 1
            self.var2b = []
            for var2 in self.var2data:
                a = Tk.IntVar()
                nRow+=1
                b = Tk.Checkbutton(self.sideMenuFrame, text=var2, variable=a)
                b.grid(row = nRow, column = 1, sticky = Tk.W)
                self.var2b.append(a)
        else:
            nRow = 1
            for var2 in self.var2data:
                nRow+=1
                b = Tk.Radiobutton(self.sideMenuFrame, text=var2, variable=self.var2, value=var2)
                b.grid(row = nRow, column = 1, sticky = Tk.W)

    def buildGraph(self):
        '''
        This method initializes the graph frame
        (Build default graph)
        '''
        dataType = self.var2.get()
        color = self.colorVar.get()
        beginYear = int(self.var3.get())
        endYear = int(self.var4.get())
        f = self.graphs.createGraphBasicBarChart(dataType, beginYear, endYear, color)
        self.graphCanvas = FigureCanvasTkAgg(f, master=self.graphFrame)
        
        self.graphCanvas.get_tk_widget().grid(row=0, column=0, sticky=Tk.W)
        self.graphCanvas.show()
        
    def updateGraph(self):
        '''
        This method updates the graph frame
        (Update graph with new options)
        '''
        dataType = self.var2.get()
        color = self.colorVar.get()
        beginYear = int(self.var3.get())
        endYear = int(self.var4.get())
        f = None
        if self.var1.get() == u'Gráfico de Barras':
            f = self.graphs.createGraphBasicBarChart(dataType, beginYear, endYear, color)
        elif self.var1.get() == u'Gráfico de Linhas':
            f = self.graphs.createGraphBasicLineChart(dataType, beginYear, endYear, color)
        elif self.var1.get() == u'Gráfico de Dispersão':
            f = self.graphs.createGraphScatterChart(dataType, beginYear, endYear, color)
        elif self.var1.get() == u'Gráfico de Linhas (Vários dados)':
            i = 0
            values = []
            for item in self.var2b:
                if item.get() == 1:
                    values.append(self.var2data[i])
                i+=1
            if len(values) == 0:
                self.var2b[0].set(1)
                values.append(self.var2data[0])
            f = self.graphs.createGraphMultipleLineChart(values, beginYear, endYear)

        self.graphCanvas = FigureCanvasTkAgg(f, master=self.graphFrame)
        self.graphCanvas.show()
        self.graphCanvas.get_tk_widget().grid(row=0, column=0, sticky=Tk.W)

    def exitApp(self):
        '''
        This method destroy the interface
        (Called from menu bar 'Exit')
        '''
        self.parent.quit()
        self.parent.destroy()
        
if __name__ == "__main__":
    root = Tk.Tk()
    gui = App(root)
    root.mainloop()
